
import { Node, _decorator } from 'cc';
import { app } from '../app-core/App';
import { InjectableComponent } from '../app-core/inject';
import { LoadingViewer } from './ui/loading/viewer/LoadingViewer';
import { UIConfig, UIID } from './UIConfigs';
const { ccclass, property } = _decorator;

/**
 * 
 * 生命周期：
 * 1、当前帧执行了onLoad：
 * 当前帧: beforeUpdate -> onLoad -> onEnable(与onDisable一样是根据active立即触发的) -> afterUpdate(当前帧并不触发update、schedule、lateUpdate，从下一帧开始)
 * 下一帧: beforeUpdate -> start -> update -> schedule -> lateUpdate -> afterUpdate
 * 之后帧: beforeUpdate -> update -> schedule -> lateUpdate -> afterUpdate
 *
 * 2、当前帧没有执行onLoad：
 * beforeUpdate -> update -> lateUpdate -> afterUpdate
 *
 * 3、touch事件更要优于beforeUpdate，但onLoad帧会不会触发不得而知
 *
 */

@ccclass('AppInit')
export class AppInit extends InjectableComponent {

    @property({ type: Node })
    private root: Node = null;

    @property({ type: Node })
    private loading: Node = null;

    private _isReady = false;

    private ui2 = true;

    onLoad() {
        super.onLoad();

        // 声明常驻根节点，该节点不会在场景切换中被销毁
        // game.addPersistRootNode(this.node);

        // 适配
        // var adapter = this.root.addComponent(UIAdapterComp);
        // view.setResizeCallback(() => {
        //     adapter.resize();
        //     this.event.emit("SCREEN_RESIZE");
        // });
    }

    start() {
        app.load();

        app.task.createSync()
            .add((next) => {
                app.ui.init(this.root, this.loading);
                app.ui.addConfigs(UIConfig);
                next();
            })
            .add((next) => {
                // var jsonPath = 'tabledata/table_gen';
                // this.loader.load(jsonPath, JsonAsset, (err: Error | null, res: JsonAsset) => {
                //     if (err) {
                //         Logger.error(err.message || err);
                //         return;
                //     }

                //     const jsonData: object = res.json!;
                //     tab.InitData(jsonData);

                //     this.loader.release(jsonPath);

                //     next();
                // })

                next();
            })
            .add((next) => {
                if (this.ui2) {
                    this.injector.getInstance('LoginFacade2')['init']();
                } else {
                    this.injector.getInstance('LoginFacade1')['init']();
                }

                next();
            })
            .start(() => {
                this._isReady = true;

                if (this.ui2) {
                    this.dispatch('Evt_Switch_Scene', 'login_scene')
                } else {
                    app.ui.open(UIID.Loading, { viewer: LoadingViewer });
                }
            })

    }

    update(dt: number) {

    }

}
